/*
 * MatPix front-end for its ANTLR lexer/parser.
 */

import java.io.*;
import antlr.CommonAST;
import antlr.debug.misc.ASTFrame;

public class Main {
  public static void main(String args[]) {
    try {
      //DataInputStream input = new DataInputStream(System.in);
    	FileInputStream input = new FileInputStream(args[0]);
    	
      // Create the lexer and parser and feed them the input
      MPLexer lexer = new MPLexer(input);
      MPParser parser = new MPParser(lexer);
      
      MPWalker treeParser = new MPWalker();
      parser.program(); // "file" is the main rule in the parser

      // Get the AST from the parser
      CommonAST parseTree = (CommonAST)parser.getAST();
      String funcDefStr = treeParser.funcDef(parseTree); 
      String programStr = treeParser.program(parseTree);  
      
      if (parser.error_count > 0) {
    	  MPException.error("Error found in the parser.");
      }
      if (lexer.error_count > 0) {
    	  MPException.error("Error found in the lexer.");
      }
      // print the program string to file
	  String forceSoftware="true;";
      FileWriter fw;
      if (args.length > 1)
      {
          String outfile = args[1];
          fw = new FileWriter (outfile);
          if (args.length > 2)
          {
        	  forceSoftware="false;";
          }
      }
      else
      {
          String infile = args[0];
          String[] split = infile.split("\\.");
          fw = new FileWriter ("cpp/" + split[0] + ".cpp");
      }      
      PrintWriter pw = new PrintWriter (fw);
      pw.println("#include \"MatPix/matpix.hpp\"");
      pw.println("");
      if (!funcDefStr.equals(""))
    	  pw.println(funcDefStr);
      pw.println("int main(){");
      pw.println("");
      pw.println("   "+"bool forceSoftwareRender=" + forceSoftware + ";");
      pw.println("   "+"initMatPix(forceSoftwareRender);");
      pw.println("");
      pw.print(programStr);
      pw.println("");
      pw.println("   "+"cleanupMatPix();");
      pw.println("   "+"return 0;");
      pw.println("}");
      pw.close();
      
      // Print the AST in a human-readable format
      //System.out.println(parseTree.toStringList());

      
      // Open a window in which the AST is displayed graphically
      if (args.length > 3)
      {
          System.out.println(funcDefStr);          
          System.out.println(programStr);    
          ASTFrame frame = new ASTFrame("AST from the MatPix parser", parseTree);
          frame.setVisible(true);
      }

    } catch(Exception e) { System.err.println("Exception: "+e); }
  }
}
